<template>
  <div class="login">
    <van-nav-bar title="登录"></van-nav-bar>
    <!-- 表单验证
          1：表单元素值的绑定
          2：写表单验证规则
          3：绑定规则
          4：触发表单验证
    -->
    <van-form class="form" ref="form">
      <van-field
        :rules="rules.mobile"
        v-model="form.mobile"
        label="手机号"
      ></van-field>
      <van-field
        :rules="rules.code"
        v-model="form.code"
        label="验证码"
      ></van-field>
      <van-button
        round
        type="info"
        class="btn"
        block
        @click="submit"
        :loading="loading"
        >登录</van-button
      >
    </van-form>
  </div>
</template>

<script>
import { authorizations } from '@/api/login'
export default {
  data () {
    return {
      loading: false,
      form: {
        mobile: '13856565651',
        code: '246810'
      },
      rules: {
        mobile: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请正确输入手机号',
            trigger: 'onChange'
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'onChange' },
          {
            pattern: /^\d{6}$/,
            message: '请输入6位验证码',
            trigger: 'onChange'
          }
        ]
      }
    }
  },
  methods: {
    // 登录
    async submit () {
      await this.$refs.form.validate()
      try {
        this.$toast({
          type: 'loading',
          duration: 0
          // forbidClick: true
        })
        this.loading = true
        const res = await authorizations(this.form)
        // 成功提示
        this.$toast.success('登录成功')
        console.log('登录返回值', res)
        // 存储token
        this.$store.commit('user/setTokenObj', res.data)
        // 跳转路由
        this.$router.push(this.$route.query.redirect || '/')
      } catch (e) {
        // this.$toast.fail(e.response.data.message)
        // console.log('错误信息', e)
      } finally {
        // 不管成功与失败都会执行
        this.loading = false
      }
    }
  }
}
</script>
<style lang="less">
.form {
  padding: 10px;
  .btn {
    margin-top: 20px;
  }
}
</style>
